# -*- coding:utf-8 -*-
from flask import request,abort,current_app,jsonify,make_response,json,session
from . import api
from ihome.utils.captcha.captcha import captcha
from ihome import redis_store,db
from ihome import constants
from ihome.utils.response_code import RET
import re,random
from ihome.utils.sms import CCP
from ihome.models import User
from ihome.utils.common import login_required

@api.route('/users',methods =["POST"])
def register():
    data_dict = request.get_json()
    mobile = data_dict.get('mobile')
    phonecode = data_dict.get('phonecode')
    password = data_dict.get('password')

    if not all([mobile,phonecode,password]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不完整')

    try:
        sms_code = redis_store.get("SMS_"+mobile)
        redis_store.delete("SMS_"+mobile)
    except Exception as e:
        sms_code = None
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='验证码获取失败')

    if not sms_code:
        return jsonify(errno=RET.NODATA, errmsg='验证码过期')

    if phonecode != sms_code:
        return jsonify(errno=RET.DBERR, errmsg='验证码错误')



    user = User()
    user.name = mobile
    user.mobile = mobile
    user.password = password

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储用户失败')

    session["name"] = mobile
    session["mobile"] = mobile
    session["user_id"] = user.id

    return jsonify(errno=RET.OK, errmsg='注册成功')


@api.route("/session",methods = ["POST"])
def login():
    data_dict = request.json
    mobile = data_dict.get("mobile")
    password = data_dict.get("password")
    print mobile,password
    if not all([mobile,password]):
        return jsonify(errno = RET.PARAMERR,errmsg = "参数不完整")

    try:
        user = User.query.filter_by(mobile = mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库获取数据失败")

    if not user:
        return jsonify(errno=RET.DATAEXIST, errmsg="用户不存在")

    if not user.check_password(password):
        return jsonify(errno=RET.PWDERR, errmsg="密码或用户名错误")

    session["name"] = user.name
    session["mobile"] = user.mobile
    session["user_id"] = user.id

    return jsonify(errno=RET.OK, errmsg='登陆成功')


@api.route("/session",methods=["DELETE"])
@login_required
def logout():
    session.pop("name", None)
    session.pop("mobile", None)
    session.pop("user_id", None)
    return jsonify(errno=RET.OK, errmsg="OK")


@api.route("/session")
def check_user_login():
    user_id = session.get("user_id")
    name = session.get("name")

    return jsonify(errno=RET.OK,errmsg="OK",data={"user_id":user_id,"name":name})